import axios from 'axios'
import qs from 'qs'

// import { useUserStore } from '@/store/modules/user'

const service = axios.create({
  baseURL: '',
})

// 待定请求集合
const pendingRequest = new Map()

/**
 * @description: 生成唯一key
 * @param {*} config axios config
 * @return {*}
 */
function generateRequestKey(config) {
  const { url, method } = config

  return [url, method].join('&')
}

/**
 * @description: 添加待定请求
 * @param {*} config axios config
 */
function addPendingRequest(config) {
  const key = generateRequestKey(config)

  if (!pendingRequest.has(key)) {
    config.cancelToken = new axios.CancelToken((cancel) => {
      pendingRequest.set(key, cancel)
    })
  }
}

/**
 * @description: 删除待定请求
 * @param {*} config axios config
 */
function removePendingRequest(config) {
  const key = generateRequestKey(config)

  if (pendingRequest.has(key)) {
    const cancelToken = pendingRequest.get(key)

    cancelToken(key)

    pendingRequest.delete(key)
  }
}

// 设置请求拦截器
service.interceptors.request.use((config) => {
  // TODO
  // const userStore = useUserStore()

  // if (userStore.token)
  //   config.headers.Authorization = userStore.token

  if (!config.isRequest && config.method === 'post') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    config.data = qs.stringify(config.data, { allowDots: true, encodeValuesOnly: true, arrayFormat: 'repeat' })
  }

  // 默认不开启
  if (config.isCancelToken) {
    removePendingRequest(config)
    addPendingRequest(config)
  }

  return config
})

// 设置响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.config.isCancelToken)
      removePendingRequest(res.config)

    return res
  },
  (error) => {
    if (error.config.isCancelToken)
      removePendingRequest(error.config)

    return Promise.reject(error)
  },
)

export default service
